﻿using Caliburn.Micro;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using SmallTune.Models;
using SmallTune.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;

namespace SmallTune
{
    /// <summary>
    /// This is the SmallTune Bootstrapper. He takes care of a good startup for the whole application.
    /// </summary>
    public class SmallTuneBootStrapper : Bootstrapper<PlayerViewModel>
    {
        private CompositionContainer container;

        protected override void OnStartup(object sender, StartupEventArgs e)
        {
            //Create database
            ISessionFactory fact = SessionFactory.session;

            //Fresh Database?
            if (SessionFactory.CreatedDB)
            {
            }
            base.OnStartup(sender, e);
        }

        protected override void Configure()
        {
            container = new CompositionContainer(new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>()));

            CompositionBatch batch = new CompositionBatch();

            //batch.AddExportedValue<IWindowManager>(new WindowManager());
            batch.AddExportedValue<IEventAggregator>(new EventAggregator());
            batch.AddExportedValue(container);

            container.Compose(batch);
        }
        
        protected override object GetInstance(Type serviceType, string key)
        {
            string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(serviceType) : key;
            var exports = container.GetExportedValues<object>(contract);

            if (exports.Count() > 0)
            {
                return exports.First();
            }

            throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
        }
        /*
        public void CreateAppDataEnvironment()
        {
            //Get the Applicationfolder
            string AppPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
            string smallTuneFolder = AppPath + @"\SmallTune";

            //Check for the SmallTune - Folder in AppData
            if (!Directory.Exists(smallTuneFolder))
            {
                Directory.CreateDirectory(smallTuneFolder);
            }

            //Set the global Folder
            (Application.Current as SmallTune.App).appDataFolder = smallTuneFolder;
        }

        public static ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
              .Database(
                SQLiteConfiguration.Standard
                  .UsingFile((Application.Current as SmallTune.App).dbPath)
              )
              .Mappings(m =>
                m.FluentMappings.AddFromAssemblyOf<SmallTuneBootStrapper>())
              .BuildSessionFactory();
        }

        public void CreateDatabase()
        {
            
            string SmallTuneDB = (Application.Current as SmallTune.App).appDataFolder + @"\SmallTune.db";
            (Application.Current as SmallTune.App).dbPath = SmallTuneDB;

            //SmallTune - DB
            if (!File.Exists(SmallTuneDB))
            {
                ISessionFactory test = CreateSessionFactory();

                //Creating the first entry in the database, called "DefaultPlaylist";
                using (var session = test.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        var playlist = new Playlist { name = "DefaultPlaylist" };
                        session.SaveOrUpdate(playlist);
                        transaction.Commit();
                    }

                }
            }
        }

        public void ShowMainWindow()
        {
            //Everything is cool, show the main window
            Application.Current.MainWindow = new MainWindow();

            //Show the MainWindow
            Application.Current.MainWindow.Show();
        }

        private void BuildSchema(Configuration config)
        {
            // this NHibernate tool takes a configuration (with mapping info in)
            // and exports a database schema from it
            new SchemaExport(config)
                .Create(false, true);
        }*/
    }
}
